package io.gitee.devaper.starlight.security.handler

import io.gitee.devaper.starlight.common.entity.vo.*
import io.gitee.devaper.starlight.common.util.*
import io.gitee.devaper.starlight.security.*
import io.gitee.devaper.starlight.security.constant.*
import jakarta.servlet.http.*
import org.springframework.context.MessageSource
import org.springframework.context.MessageSourceAware
import org.springframework.security.core.*
import org.springframework.security.web.authentication.AuthenticationSuccessHandler
import org.springframework.stereotype.Component

/**
 * 认证成功处理器
 */
@Component
open class DefaultAuthenticationSuccessHandler : AuthenticationSuccessHandler, MessageSourceAware {
    override fun onAuthenticationSuccess(
        request: HttpServletRequest,
        response: HttpServletResponse,
        authentication: Authentication
    ) {
        // 检查principal存储的UserDetails类型
        val principal = authentication.principal
        if (principal is DefaultUserDetails) {
            val vo = UserVO.valueOf(principal.user)
            response.write(data = ApiResult.success(vo), request = request)
        } else {
            response.write(
                data = ApiResult.error(messageSource.getMessage(MS_AUTHENTICATION_FAILURE_WRONG_DETAILS, null, request.locale)),
                request = request
            )
        }
    }

    private lateinit var messageSource: MessageSource

    override fun setMessageSource(messageSource: MessageSource) {
        this.messageSource = messageSource
    }
}